/*========= Starting function =========*/
$(function() {
    $(document).ready(function() {
        $('.dataTables_length select').chosen();
    });
    novel.init();
});

var novel = (function() {

    function novelForm_validate() {
        var error = true,
            name = $('#name').val(),
            oname = $('#oname').val(),
            author = $('#author').val(),
            desc = $('#desc').val();

        if (!name || name.length > 100) {
            $('#name').addClass('error');
            error = false;
        }

        if (oname && oname.length > 100) {
            $('#oname').addClass('error');
            error = false;
        }

        if (author && author.length > 100) {
            $('#author').addClass('error');
            error = false;
        }

        if (desc && desc.length > 2000) {
            $('#desc').addClass('error');
            error = false;
        }

        return error;
    }

    function novelForm_reset(flag) {
        $('input[type=text]').removeClass('error');
        $('#err_msg').hide().find('.alert').attr('class', 'alert alert-error noMargin');
        if (flag) {
            $('input[type=text]').val('');
            $('#cover').val('');
            $('#err_msg .alert').html('');
        }
    }

    function addNovel_handler() {
        $('#add_new_manga_submit').click(function() {
            novelForm_reset();
            if (novelForm_validate()) {
                var url = '/novel/ajax_add_new_novel';
                var cats = [];
                $('input:checkbox[name=cats]:checked').each(function(i, item) {
                   cats.push($(item).val()); 
                }); 
                $.ajax({
                    type: "POST",
                    url: url,
                    data: {
                        name: $('#name').val(),
                        oname: $('#oname').val(),
                        author: $('#author').val(),
                        desc: $('#desc').val(),
                        translator: $('#translator').val(),
                        status: $('input:radio[name=status]:checked').val(),
                        cover: $('#cover_hidden').val(),
                        cats: cats.join(',')
                    },
                    dataType: 'json',
                    success: function(resp) {
                        if (resp.err != 0) {
                            for (var i in resp.msg)
                                $('#' + i).addClass('error');
                            var msg,
                                err = resp.err;
                            switch (err) {
                                case -3:
                                    msg = 'Novel name exist.';
                                    break;
                                default:
                                    msg = 'Something wrong, please check again.';
                            }
                            $('#manga_add_new #err_msg').show().find('.alert').attr('class', 'alert alert-error noMargin').html(msg);
                        } else if (resp.err == 0) {
                            $('#manga_add_new #err_msg').show().find('.alert').attr('class', 'alert alert-success noMargin').html('Successfull.');
                            window.location.href = '/novel/edit/' + resp.id;
                        }
                    }
                });
            } else {
                $('#manga_add_new #err_msg').show().find('.alert').attr('class', 'alert alert-error noMargin').html('Something wrong, please check again.');
            }
            return false;
        });

        $('#add_new_manga_reset').click(function() {
            novelForm_reset(true);
            return false;
        });
    }

    function uploadCover_handler() {
        var uploader = new plupload.Uploader({
            runtimes: 'html5,browserplus',
            browse_button: 'uploadCover',
            drop_element: 'uploadCover',
            max_file_size: '5mb',
            multipart: true,
            unique_names: true,
            url: '/novel/ajax_upload_novel_cover',
            multi_selection: false,
            filters: [{title: "Image files", extensions: "jpg,gif,png"}]
        });
        uploader.init();
        uploader.bind('FilesAdded', function(up, files) {
            $('.coverErr ul').html('');
            $('.wTitle .coverLoading').css('opacity', '1');
            console.log('uploader.start()');
            uploader.start();
        });

        uploader.bind('FileUploaded', function(up, file, info) {
            var resp = JSON.parse(info.response);
            console.log('uploader.bind: ' + resp)
;            if (resp.err == 0 && resp.furl) {
                var url = resp.furl.replace(/\\\//g, '/');
                $('#uploadCover').removeClass('uploadCover').html('<img id="cover" src="' + url + '" />');
                $('#cover_hidden').val(resp.cover_path);
            } else {
                $('.coverErr ul').html('<li>' + resp.msg + '</li>');
            }
            $('.wTitle .coverLoading').css('opacity', '0');
        });
    }

    function editNovel_handler() {
        $('#edit_manga_submit').click(function() {
            novelForm_reset();
            if (novelForm_validate()) {
                var url = '/novel/ajax_edit_novel';
                var cats = [];
                $('input:checkbox[name=cats]:checked').each(function(i, item) {
                   cats.push($(item).val()); 
                });
                $.ajax({
                    type: "POST",
                    url: url,
                    data: {
                        id: $('#manga_id').val(),
                        name: $('#name').val(),
                        oname: $('#oname').val(),
                        author: $('#author').val(),
                        translator: $('#translator').val(),
                        desc: $('#desc').val(),
                        cover: $('#cover_hidden').val(),
                        status: $('input:radio[name=novel_status]:checked').val(),
                        cats: cats.join(',')
                    },
                    dataType: 'json',
                    success: function(resp) {
                        if (resp.err == 0) {
                            $('#manga_slug').val(resp.slug);
                            $('#manga_edit #err_msg').show().find('.alert').attr('class', 'alert alert-success noMargin').html('Successfull.');
                        } else if (resp.err != 0) {
                            for (var i in resp.msg)
                                $('#' + i).addClass('error');
                            var msg, err = resp.err;
                            switch (err) {
                                case -3:
                                    msg = 'Novel name exist.';
                                    break;
                                default:
                                    msg = 'Something wrong, please check again.';
                            }
                            $('#manga_edit #err_msg').show().find('.alert').attr('class', 'alert alert-error noMargin').html(msg);
                        }
                    }
                });
            } else {
                $('#manga_edit #err_msg').show().find('.alert').attr('class', 'alert alert-error noMargin').html('Something wrong, please check again.');
            }
            return false;
        });

        // Remove User
        $('.editRemoveManga').click(function() {
            var id = $(this).attr('id').replace('removeManga_', ''),
                name = $(this).attr('rel'),
                info = '<br/><p>Are you sure to delete the Manga with name <span class="text-error">' + name + '</span>?<br/><br/>';
            showConfirm({
                title: 'Delete user',
                msg: info,
                warning: '<p class="text-warning" align="left">Please understand that this action cannot be reverted. </p>',
                noBt: 'No, not now.',
                yesBt: 'Delete.',
                onYes: function() {
                    var url = '/novel/ajax_remove_novel';
                    $.ajax({type: "POST", url: url, data: {id: id}, dataType: 'json',
                        success: function(resp) {
                            if (resp.err != 0)
                                showAlert('Something wrong, please try again later.');
                            else if (resp.err == 0) {
                                window.location = '/novel';
                            }
                        }
                    });
                }
            });
            return false;
        });

        //Sort picture
        $("#sortable").sortable({
            update: function(event, ui) {
                $(ui.item[0]).attr('style', '');
            }
        });
    }

    function allNovel_hanlder() {
        $('#list_all_manga .removeManga').click(function() {
            var id = $(this).attr('id').replace('removeManga_', ''),
                name = $(this).attr('rel'),
                info = '<br/><p>Are you sure to delete the Manga with name <span class="text-error">' + name + '</span>?<br/><br/>';
            showConfirm({
                title: 'Delete manga',
                msg: info,
                warning: '<p class="text-warning" align="left">Please understand that this action cannot be reverted. </p>',
                noBt: 'No, not now.',
                yesBt: 'Delete.',
                onYes: function() {
                    var url = '/novel/ajax_remove_novel';
                    $.ajax({type: "POST", url: url, data: {id: id}, dataType: 'json',
                        success: function(resp) {
                            if (resp.err != 0)
                                showAlert('Something wrong, please try again later.');
                            else if (resp.err == 0) {
                                $('#mangaRow_' + id).remove();
                            }
                        }
                    });
                }
            });
            return false;
        });
    }

    return {
        init: function() {
            addNovel_handler();
            uploadCover_handler();
            editNovel_handler();
            allNovel_hanlder();
        }
    };
})();